<?php

namespace Common\Logic;

/**
 * Description of 管理员登录业务逻辑层
 *
 * @author zhangzhen
 * @date 2017-1-4
 */
class DealerLoginLogic extends \Common\Controller\BaseController {

    /**
     * 登陆验证
     * @modify zhangzhen 2016-01-08
     * @param string $mobile  手机号
     * @param string $password 密码
     */
    public function login($mobile, $password, $areaCode = '86') {
        $dealerLoginModel = D('DealerLogin');
        $dealerLogin = $dealerLoginModel->getInfoByMobile($mobile, $areaCode);
        if (empty($dealerLogin)) {
            returnJson(403, 100);
        }
        if ($dealerLogin['password'] != $password) {
            returnJson(403, 101);
        }
        //查询
        $dealerInfoModel = D('DealerInfo');
        $dealerInfo = $dealerInfoModel->getInfoByUser($dealerLogin['id']);
        unset($dealerInfo['id']);
        unset($dealerInfo['dealerlogin_id']);
        //组合数据
        return array_merge($dealerLogin, $dealerInfo);
    }
    public function getInfo($userId) {
        return $this->__singleGet('_getInfo', array($userId));
    }
    /**
     * 获取经销商信息
     * @param  int $userId 经销商id
     * @return array       经销商信息
     */
    public function _getInfo($userId) {
        $dealerLoginModel = D('DealerLogin');
        $dealerLogin = $dealerLoginModel->getInfo($userId);
        if (!$dealerLogin) {
            return array();
        }
        $dealerInfoModel = D('DealerInfo');
        $dealerInfo = $dealerInfoModel->getInfoByUser($userId);
        unset($dealerInfo['id']);
        unset($dealerInfo['dealerlogin_id']);
        return array_merge($dealerLogin, $dealerInfo);
    }

    /**
     * 更新用户数据
     * @modfiy zhangzhen 2017-01-04
     * @param integer $userId  用户ID
     * @param string $name  用户名称
     * @param string $headpath  用户头像
     */
    public function saveInfo($userId, $name, $headpath) {
        $dealerLoginModel = D('DealerLogin');
        //检查数据
        $dealerLogin = $dealerLoginModel->getInfo($userId);
        if (!$dealerLogin) {
            returnJson(500, 501);
        }

        $dealerLoginModel->startTrans();
        $commit = true;
        $result = $dealerLoginModel->setName($userId, $name);
        if ($result == false) {
            $commit = false;
        }
        $dealerInfoModel = D('DealerInfo');
        if ($commit) {
            $result = $dealerInfoModel->saveInfo($userId, $headpath);
            if ($result == false) {
                $commit = false;
            }
        }
        if ($commit) {
            $dealerInfoModel->commit();
        } else {
            $dealerLoginModel->rollback();
            returnJson(500, 509);
        }
    }

}
